package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateTimeZoneConverter;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 设备Service业务层处理
 * 
 * @author alexis
 * @date 2025-08-22
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private IoTDAClient ioTDAClient;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 查询设备
     * 
     * @param id 设备主键
     * @return 设备
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备列表
     * 
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备
     * 
     * @param device 设备
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备
     * 
     * @param device 设备
     * @return 结果
     */
    @Override
    public int updateDevice(Device device)
    {
        return updateById(device) ? 1 : 0;
    }

    /**
     * 批量删除设备
     * 
     * @param ids 需要删除的设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }



    /**
     * 删除设备信息
     * 
     * @param id 设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    @Override
    public void getProductList() {
        ListProductsRequest request = new ListProductsRequest();
        request.setLimit(50);
        ListProductsResponse response = ioTDAClient.listProducts(request);
        if(response.getHttpStatusCode()!=200)
        {
            throw  new BaseException("从IOT平台获取产品列表失败");
        }
        //存储到redis中
        redisTemplate.opsForValue().set(CacheConstants.IOT_ALL_PRODUDCUT_LIST, JSONUtil.toJsonStr(response.getProducts()));
    }



    /**
     * 从redis中获取所有产品列表
     * @return
     */
    @Override
    public List<ProductVo> getAllProduct() {
        //
        String Products = redisTemplate.opsForValue().get(CacheConstants.IOT_ALL_PRODUDCUT_LIST);
        if(ObjectUtil.isEmpty(Products))
        {
            return Collections.emptyList();
        }

        //将字符串转换成Json格式的集合
        List<ProductVo> list = JSONUtil.toList(Products, ProductVo.class);
        return list;
    }




    /**
     * 添加设备
     * @param deviceDto
     */
    @Override
    public void addDevice(DeviceDto deviceDto) {

        if(deviceDto.getLocationType()==0)
        {
            deviceDto.setPhysicalLocationType(-1);
        }

        //判断设备名称是否重复
        long count = count(Wrappers.<Device>lambdaQuery().eq(Device::getDeviceName, deviceDto.getDeviceName()));
        if(count>0){
            throw new BaseException("设备名称重复,请重新输入");
        }
        //判断标识是否重复node_id
        count(Wrappers.<Device>lambdaQuery().eq(Device::getNodeId, deviceDto.getNodeId()));
        if(count>0){
            throw new BaseException("设备标识码重复,请重新输入");
        }
        //判断同一位置是否绑定了相同的产品
        long count1 = count(Wrappers.<Device>lambdaQuery()
                .eq(Device::getBindingLocation, deviceDto.getBindingLocation())
                .eq(Device::getLocationType, deviceDto.getLocationType())
                .eq(Device::getPhysicalLocationType, deviceDto.getPhysicalLocationType())
                .eq(Device::getProductKey, deviceDto.getProductKey()));
        if(count1>0){
            throw new BaseException("同一位置已绑定相同产品,请重新选择");
        }
        //注册设备
        AddDeviceRequest request = new AddDeviceRequest();

        AddDevice body=new AddDevice();
        body.setProductId(deviceDto.getProductKey());
        body.setNodeId(deviceDto.getNodeId());
        body.setDeviceName(deviceDto.getDeviceName());
        AuthInfo authinfo =new AuthInfo();
        String secret= UUID.randomUUID().toString().replace("-","");
        authinfo.setSecret(secret);
        body.setAuthInfo(authinfo);

        request.setBody(body);
        AddDeviceResponse response;
        try {
             response = ioTDAClient.addDevice(request);
        } catch (Exception e) {
            throw new BaseException("设备注册失败");
        }


        //本地保存设备
        //属性拷贝
        Device device = BeanUtil.copyProperties(deviceDto, Device.class);
        //设置设备密钥
        device.setSecret(secret);
        //设置设备id
        device.setIotId(response.getDeviceId());
        save(device);
    }




    /**
     * 查看设备详细信息
     * @param iotId
     * @return
     */
    @Override
    public DeviceDetailVo getDeviceDetail(String iotId) {
        //从数据库中查找一些数据
        Device device = getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));

        //从华为云中获取到设备的创建时间和设备状态
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response;
        try {
            response = ioTDAClient.showDevice(request);
        } catch (Exception e) {
            throw new BaseException("查询设备详细信息失败");
        }

        String activeTime = response.getActiveTime();//获取创建时间


        LocalDateTime activeTimeLocalDateTime =null;
        if(StringUtils.isNotEmpty(activeTime))
        {
            //将字符串转换成LocalDataTime时间
            activeTimeLocalDateTime = LocalDateTimeUtil.parse(activeTime, DatePattern.UTC_MS_PATTERN);
            //将时区设置成上海时区
            activeTimeLocalDateTime= DateTimeZoneConverter.utcToShanghai(activeTimeLocalDateTime);

        }
        //合并封装数据
        //属性拷贝
        DeviceDetailVo deviceDetailVo = BeanUtil.copyProperties(device, DeviceDetailVo.class);
        deviceDetailVo.setDeviceStatus(response.getStatus());
        deviceDetailVo.setActiveTime(activeTimeLocalDateTime);
        return deviceDetailVo;
    }



    /**
     * 获取设备上报数据(设备影子)
     * @param iotId
     * @return
     */
    @Override
    public AjaxResult getDeviceDataShow(String iotId) {
        //从华为云中获取到设备影子
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse response;
        try {
             response = ioTDAClient.showDeviceShadow(request);
        } catch (Exception e) {
            throw new BaseException("查询设备上报数据失败");
        }
        //解析response中的数据
        List<DeviceShadowData> shadow = response.getShadow();
        //判断是否为空
        if(CollectionUtils.isEmpty(shadow))
        {
            return AjaxResult.success(Collections.emptyList());
        }
        //获取reported中的properties数据,这里将这个properties的数据转换成jsonsObject类型的数据,jsonObject数据其实就是map类型的集合数据
        DeviceShadowProperties reported = shadow.get(0).getReported();

        JSONObject jsonObject = JSONUtil.parseObj(reported.getProperties());

        //解析event_time数据  将这个时间数据的格式进行调整以及时区的调整
        String eventTimeStr = reported.getEventTime();
        //将字符串转换成LocalDateTime类型的数据
        LocalDateTime parse = LocalDateTimeUtil.parse(eventTimeStr, DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'"));
        LocalDateTime evenTime = DateTimeZoneConverter.utcToShanghai(parse);

        //封装结果数据
        List<Map<String,Object>> result=new ArrayList<>();

        //遍历jsonObject,
        jsonObject.forEach((key,value)->{
            Map<String,Object> map=new HashMap<>();
            map.put("eventTime",evenTime);
            map.put("functionId",key);
            map.put("value",value);
            result.add(map);
        });

        return AjaxResult.success(result);
    }

    /**
     * 修改设备
     * @param device
     */
    @Override
    public void updateDeviceIOT(Device device) {
        if(device.getLocationType()==0)
        {
            device.setPhysicalLocationType(-1);
        }

        //1.先修改华为云中的设备信息,只能修改华为云中这个设备名称
        UpdateDeviceRequest request = new UpdateDeviceRequest();

        //设置
        request.setDeviceId(device.getIotId());//1.设置设备id
        UpdateDevice body=new UpdateDevice();
        body.setDeviceName(device.getDeviceName());//2.设置设备名称

        request.setBody(body);//设置参数

        try {
            ioTDAClient.updateDevice(request);
        } catch (Exception e) {
            throw new BaseException("修改设备名称信息失败");
        }

        //2.修改本地信息

        try {
            updateById(device);
        } catch (Exception e) {
            throw new BaseException("该老人/该位置已绑定该类型的设备,请重新选择绑定位置");
        }

    }


    /**
     * 删除设备
     * @param iotId
     */
    @Override
    public void deleteDeviceByIdIOT(String iotId) {
        //1.首先删除华为云中的设备
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.setDeviceId(iotId);//设备id
        try {
            ioTDAClient.deleteDevice(request);
        } catch (Exception e) {
            throw new BaseException("设备删除失败");
        }

        //2.删除本地设备数据

        boolean remove = remove(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));

    }


    /**
     * 查询产品信息
     * @param productKey
     * @return
     */
    @Override
    public AjaxResult queryProduct(String productKey) {
        //1.验证产品key
        if(StringUtils.isEmpty(productKey))
        {
            throw new BaseException("产品key不存在");
        }
        //2.从华为云中获取到相关数据
        ShowProductRequest showProductRequest = new ShowProductRequest();
        showProductRequest.setProductId(productKey);
        ShowProductResponse response;
        try {
             response = ioTDAClient.showProduct(showProductRequest);
        } catch (Exception e) {
            throw new BaseException("查询产品信息失败");
        }
        //3.解析数据
        List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();
        if(CollectionUtils.isEmpty(serviceCapabilities)){
            return AjaxResult.success(Collections.emptyList());
        }

        return AjaxResult.success(serviceCapabilities);
    }

}
